<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
        <title>Promise状态</title>
    </head>
    <body>
        <h3>请在终端中查看Promise的状态</h3>

        <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise">
            标准内置对象: Promise
        </a>

        <hr>

        <button class="fulfill">兑现</button>
        <button class="reject">拒绝</button>

        <script type="text/javascript">

            const type = 'click';
            const capture = false ;
            const btn1 = document.querySelector( '.fulfill' );
            const btn2 = document.querySelector( '.reject' );

            let executor = ( resolve , reject ) => {
                // 为 btn1 绑定 type 事件的监听器
                btn1.addEventListener( type , evt => resolve('你好坏哦!我好喜欢!') , capture );
                // 为 btn2 绑定 type 事件的监听器
                btn2.addEventListener( type , evt => reject('你是个好人') , capture );
            }
            const firstPromiseInstance = new Promise(executor);
            console.table(firstPromiseInstance);

            // 当 Promise实例 变成 兑现状态（fulfilled）时调用的函数
            let onFulfilled = theFulfillmentValue => {
                console.log( 'the fulfillment value: ' , theFulfillmentValue );
                console.log( '- - - firstPromiseInstance - - -' );
                console.table( firstPromiseInstance );
                console.log( '- - - secondPromiseInstance - - -' );
                console.table( secondPromiseInstance );
            }

            // 当 Promise实例 变成 拒绝状态（rejected） 时调用的函数
            let onRejected = rejectionReason => {
                console.log( 'rejection reason: ' , rejectionReason );
                console.log( '- - - firstPromiseInstance - - -' );
                console.table( firstPromiseInstance );
                console.log( '- - - secondPromiseInstance - - -' );
                console.table( secondPromiseInstance );
            }

            // 1、当调用 then 函数时，它会立即执行并返回 Promise实例
            // 2、未来，若 Promise实例 的状态已经转换为 fulfilled 状态，则异步调用 then 的第一个参数对应的函数(onFulfilled)
            // 2、未来，若 Promise实例 的状态已经转换为 rejected 状态，则异步调用 then 的第二个参数对应的函数(onRejected)
            const secondPromiseInstance = firstPromiseInstance.then( onFulfilled , onRejected );
            console.log( secondPromiseInstance );

            const thirdPromiseInstance = secondPromiseInstance.then( onFulfilled , onRejected );
            console.log( thirdPromiseInstance );
        </script>
    </body>
</html>